import { defineStore } from 'pinia'
import { StateType } from './typing'
import { getToken, getUserInfo, refreshToken } from '@/api/user'
import { setOauth, clearOauth, setCacheUserInfo, clearCacheUserInfo } from '@/utils/auth'

// store名称
const storeName = 'user'

const initState: StateType = {
  oauth: {
    refresh_token: '',
    access_token: '',
    token_type: '',
    expires_at: 0,
  },
  currentUser: {
    id: 0,
    name: '',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    roles: ['admin'],
  },
  message: 0,
  loginStatus: undefined,
}

export const useUserStore = defineStore(storeName, {
  state: (): StateType => ({
    ...initState,
  }),
  actions: {
    async login(payload) {
      let status: string | undefined = undefined
      try {
        const res: any = await getToken(payload)
        if (res.success) {
          this.oauth = res.data
          await setOauth(res.data)

          const { data: userInfo } = await getUserInfo(res.data.access_token)
          this.currentUser = { ...this.currentUser, ...userInfo }
          await setCacheUserInfo(userInfo)

          status = 'ok'
        } else {
          throw res.message
        }
      } catch (error) {
        console.log(error)

        if ((error as any).message && (error as any).message === 'CustomError') {
          status = 'error'
        }
      }

      this.changeLoginStatus(status)
      if (status === 'ok') {
        return true
      } else if (status === 'error') {
        return false
      }
      return undefined
    },

    // async refreshToken() {
    //   const res = await refreshToken(this.oauth.refresh_token)
    //   console.log(res)
    // },

    changeLoginStatus(payload) {
      this.loginStatus = payload
    },
    saveCurrentUser(payload) {
      this.currentUser = {
        ...initState.currentUser,
        ...payload,
      }
    },

    async logout() {
      return new Promise(async (resolve) => {
        this.oauth = initState.oauth
        this.currentUser = { ...initState.currentUser }
        this.message = 0
        this.loginStatus = undefined
        await clearOauth()
        await clearCacheUserInfo()
        resolve(true)
      }) as Promise<boolean>
    },
  },
})
